package czk.concrent.synControl.practice;

import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/24 11:25
 */
public class WaitTest {
    public static void main(String[] args) {
        WaitAndNotify waitAndNotify=new WaitAndNotify(6,"1");
        new Thread(()->{
            waitAndNotify.print("1","1","2");
        }).start();
        new Thread(()->{
            waitAndNotify.print("2","2","3");
        }).start();
        new Thread(()->{
            waitAndNotify.print("3","3","1");
        }).start();
    }
}

class WaitAndNotify {
    /**
     * 定义循环次数
     */
    private int loopNum;
    /**
     * 定义此时的标记
     */
    private String flag;

    /**
     * @param loopNum
     */
    public WaitAndNotify(int loopNum,String flag) {
        this.loopNum = loopNum;
        this.flag=flag;
    }


    /**
     * 打印方法
     *
     * @param content
     * @param flag
     * @param nextFlag
     */
    public void print(String content, String flag, String nextFlag) {
        for (int i = 0; i < loopNum; i++) {
            // 锁住当前对象
            synchronized (this) {
                while (!Objects.equals(this.flag, flag)) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 打印
                System.out.print(content);
                // 替换标记
                this.flag = nextFlag;
                // 唤醒阻塞线程
                this.notifyAll();
            }

        }
    }
}
